<template>
    <div class="form-page">
        <el-form
            ref="form"
            :model="form"
            label-width="8em"
            :rules="courseFormRules"
            class="data-form"
        >
            <div class="form-item xy-start al-str">
                <div class="title">文章资讯</div>
                <div class="yx-start al-start data">
                    <el-form-item label="所属学科" prop="categoryId">
                        <category-select
                            :category-id.sync="form.categoryId"
                            :props="{}"
                        />
                    </el-form-item>
                    <el-form-item
                        style=""
                        label="标题"
                        prop="title"
                        size="mini"
                    >
                        <el-input v-model="form.title"></el-input>
                    </el-form-item>

                    <el-form-item
                        style="width:50%"
                        label="排序"
                        prop="sort"
                        size="mini"
                    >
                        <el-input v-model="form.sort"></el-input>
                    </el-form-item>

                    <el-form-item label="是否置顶推荐" prop="top">
                        <el-switch
                            v-model="form.top"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            @change="changeTH('top')"
                        >
                        </el-switch>
                    </el-form-item>
                    <el-form-item label="是否飘红推荐" prop="hot">
                        <el-switch
                            v-model="form.hot"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            @change="changeTH"
                        >
                        </el-switch>
                    </el-form-item>
                    <el-form-item label="是否置顶热点" prop="recommend">
                        <el-switch
                            v-model="form.recommend"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                        >
                        </el-switch>
                    </el-form-item>
                    <el-form-item label="结构类型" prop="type">
                        <el-radio-group v-model="form.type" >
                            <el-radio :label="false" :disabled="radioFlag">资讯</el-radio>
                            <el-radio :label="true" :disabled="radioFlag">资料</el-radio>
                        </el-radio-group>
                    </el-form-item>
<!--
                    <el-form-item label="封面" prop="cover" :class="{'is-required':coverRequired}">
                        <div style="display: flex;flex-direction: row">
                            <div>
                                <upload-img
                                    v-model="form.cover"
                                    :cover="form.cover"
                                    :size="5*1024*1024"
                                    @courseCoverImg="courseCoverImg"
                                >
                                </upload-img>
                            </div>

                            <div style="margin-left: 50px;margin-top: 40px;">
                                <span style="color: red;">
                                    推荐说明:
                                </span>
                                <span>
                                    支持jpg/gif/png格式,建议尺寸600x332px,5M以内
                                </span>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="摘要" prop="summary">
                        <el-input
                            v-model="form.summary"
                            type="textarea"
                            size="large"
                            :rows="10"
                            autosize
                            maxlength="80"
                            show-word-limit
                            placeholder="请输入内容"
                        >
                        </el-input>
                    </el-form-item>
                    <el-form-item label="内容" prop="content" :required="contentRequired">
                        <tinymce v-if="queryId===undefined||(showTinymce && form.id)" v-model="form.content"/>
                    </el-form-item>
                    -->
                    <el-form-item
                        style=""
                        label="附件"
                        prop="attachmentInfos"
                        size="mini"
                        :required="attachmentRequired"
                    >

                        <el-upload
                            class="upload-demo"
                            action="https://jsonplaceholder.typicode.com/posts/"
                            multiple
                            :limit="fileLimit"
                            :auto-upload="false"
                            :on-change="onchange"
                            :on-remove="handleRemove"
                            :file-list="fileList">
                            <el-button size="small" type="primary">点击上传</el-button>

                        </el-upload>

                    </el-form-item>

                    <div>
                        <el-button
                            class="next-btn"
                            type="info"
                            :loading="submitFlag"
                            @click="clickCancel('materialInfoBase')"
                        >
                            取消
                        </el-button>
                        <el-button
                            class="next-btn"
                            type="primary"
                            :loading="submitFlag"
                            @click="saveArticle('form')"
                        >
                            保存
                        </el-button>
                    </div>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script>
import {FormPage} from "@/layout/mixin/iVue.js";

import {fetchArticleColumnChildren, fetchArticleColumnFirst} from "@/api/course.js";
import {get} from "@/api/request";
import Tinymce from "@/components/Tinymce";
import {ossUpload} from "@/utils/file.js";
import UploadImg from "@/views/models/content/materialInfoBase/UploadImg";
import CategorySelect from "@/components/CategorySelect";

export default {
    name: "MaterialInfoAddSetting",
    components: {
        Tinymce,
        UploadImg,
        CategorySelect,
    },
    mixins: [FormPage],

    data() {
        const numberPass = (rule, value, callback) => {
            let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
            if (value === "") {
                callback(new Error("请输入内容"));
            } else if (!reg.test(value)) {
                callback(new Error("请输入数字"));
            } else {
                callback();
            }
        };
        return {
            aliasRequired: false,
            radioFlag: false,
            fileLimit: 100,
            form: {examId: null, content: null, recommend: null, type: false},
            industryId: null,
            industryOptions: [],
            examOptions: [],
            attachmentInfos: "",
            fileList: [],
            fileInfos: [],
            showLinkFlag: false,
            contentRequired: false,
            attachmentRequired: false,
            coverRequired: false,
            treeProps: {
                label: "name",
                children: "children"
            },
            groupKey: 0,
            articleColumnProps: {
                lazy: true,
                checkStrictly: true,
                lazyLoad: this.getArticleColumnSta,
                emitPath: false
            },
            textarea: "",
            showExam: false,
            showTinymce: true,
            value: "",
            active: 0,
            key: 0,
            isAdd: false,
            showCa: false,

            message: "first",
            showHeader: false,
            showFlag: false,
            showCredit: false,
            showCharge: false,
            isDisabled: false,
            isUploadCover: false,
            courseFormRules: {
                title: [
                    {
                        required: true,
                        message: "请输入标题",
                        trigger: "blur"
                    },
                    {
                        min: 2,
                        max: 100,
                        message: "长度在 2 到 100 个字符",
                        trigger: "blur"
                    }
                ],
                type: [
                    {
                        required: true,
                        message: "请选择结构类型",
                        trigger: "change"
                    }
                ],
            },
            courseType: 0,
            dialogTableVisible: false,
            categories: null,
            classificationInfo: [],
            classficationQueryData: {
                size: 1000
            }
        };
    },
    watch: {
        "form.industryId"(industryId) {
            if (industryId) {
                this.initExam(industryId);
            } else {
                this.examOptions = [];
            }
        },
        "form.type"(type) {
            if (type) {
                this.contentRequired = false;
                this.attachmentRequired = true;
                this.coverRequired = false;
            } else {
                this.contentRequired = true;
                this.attachmentRequired = false;
                if (this.form.recommend) {
                    this.coverRequired = true;
                }
            }

        },
        "form.recommend"(type) {
            if (type && this.form.type !== true) {
                this.coverRequired = true;
            } else {
                this.coverRequired = false;
            }
        }

    },
    destroyed() {
        this.showTinymce = false;
    },
    created() {
        this.getIndustryOptions();
        this.showTinymce = true;
    },
    methods: {

        choseExam() {
            get("/exam/exam/exam-by-industryId", {"industryId": this.form.industryId, "size": 1000}).then(res => {
                this.examOptions = res;
                this.form.examId = null;
            });
        },
        initExam() {
            get("/exam/exam/exam-by-industryId", {"industryId": this.form.industryId, "size": 1000}).then(res => {
                this.examOptions = res;
            });
        },
        getIndustryOptions() {
            get("/exam/industry/list", {size: 1000}).then(res => {
                this.industryOptions = res;
            });
        },
        changeTH(val) {
            if (val === "top" && this.form.hot === true) {
                this.form.hot = false;
                this.form.top = true;
            } else if (val !== "top" && this.form.top === true) {
                this.form.top = false;
                this.form.hot = true;
            }
            if (this.form.hot || this.form.top) {
                this.aliasRequired = true

            } else {
                this.aliasRequired = false
            }
        },
        coverAttachmentInfos() {
            let fileList = new Set(this.fileList);
            fileList.forEach(f => {
                var fileInfo = {
                    "path": f.path,
                    "size": f.size,
                    "name": f.name
                };
                this.fileInfos.push(fileInfo)
            })


            return this.fileInfos;
        },
        handleRemove(file, fileList) {
            /* this.$confirm(`确定移除 ${file.name}？`, "提示", {
                 confirmButtonText: "确定",
                 cancelButtonText: "取消",
                 type: "warning",
                 center: true
             }).then(() => {
                 this.$message({
                     type: "success",
                     message: "删除成功!"
                 })
                 console.log("fileList", fileList);*/
            this.fileList = fileList;
            /*     console.log("this.fileList", this.fileList);
             }).catch(() => {
                 this.$message({
                     type: "info",
                     message: "已取消删除!"
                 })
             });*/
        },
        onchange(file, fileList) {
            let imgReaderl = new FileReader();
            imgReaderl.onload = evt => {
                this.base64Header = evt.target.result;
            };
            imgReaderl.readAsDataURL(file.raw);
            ossUpload("cdn", file.raw.name, file.raw, p => {
                file.percentage = p * 100;
                file.status = "uploading";
            }).then(result => {
                file.path = result;
                file.status = "done";
            });
            console.log("fileList", fileList)
            this.fileList = fileList
            console.log("this.fileList", this.fileList)
        },
        saveArticle(formName) {
            this.form.attachmentInfos = this.coverAttachmentInfos();
            console.log("附件",this.form.attachmentInfos);
            if (this.form.type && this.form.attachmentInfos === "[]") {
                this.$message.error("附件必需上传");
                return false;
            }
            this.$refs[formName].validate(valid => {
                if (!valid) {
                    console.log("error submit!!");
                    return false;
                }
            });
            if (this.addAction) {
                this.clickSave(
                    "/material/info/update",
                    this.form,
                    false,
                    "materialInfoBase"
                );
            } else {
                this.clickSave(
                    "/material/info/update",
                    this.form,
                    true,
                    "materialInfoBase"
                );
            }
        },

        showLink() {
            if (this.fileList.length > 1) {
                this.$message({
                    message: "请先移除文件",
                    type: "warning"
                });
                //不允许改变
                this.form.type = !this.form.type
                return
            }
            if (this.form.type) {
                this.fileLimit = 1
            } else {
                this.fileLimit = 100
            }
        },
        getArticleColumnSta(node, resolve) {
            const {level} = node;
            if (!node.data) {
                fetchArticleColumnFirst({
                    articleCategoryId: this.articleCategoryId
                }).then(res => {
                    const nodes = Array.from(res).map(item => {
                        return {
                            value: item.id,
                            label: `${item.name}`,
                            leaf: level >= (item.children.length > 0 ? 1 : 0)
                        };
                    });
                    resolve(nodes);
                });
            } else {
                fetchArticleColumnChildren({id: node.data.value}).then(
                    res => {
                        const nodes = Array.from(res).map(item => {
                            return {
                                value: item.id,
                                label: `${item.name}`,
                                leaf:
                                    level >=
                                    (item.children.length > 0 ? level + 1 : 0)
                            };
                        });
                        resolve(nodes);
                    }
                );
            }
        },

        async loadData(id) {
            this.isAdd = id === undefined;

            return Promise.all([this.loadCourseOld(id)]).catch(e => {
                this.$message.error("数据加载失败，请稍后在试");
            });
        },
        async loadCourseOld(id) {
            if (!id) {
                this.showFlag = true
                return;
            }

            get(`/material/info/detail/${id}`).then(result => {

                this.dataForm = result;
                if (result.attachmentInfos) {
                    this.fileList=result.attachmentInfos

                }
                this.chargeForm = result;
                this.isDisabled = true;
                this.form = result;
                this.showFlag = true
                this.showExam = true
                this.radioFlag = true
            });
        },
        //封面
        courseCoverImg(url) {
            this.form.cover = url;
            this.isUploadCover = true
            this.$refs.form.validateField("cover")
        }
    }
};
</script>

<style lang="css" scoped>
.next-btn {
    margin-left: 12px;
}

.course-table-edit-from .el-textarea {
    width: 60em;
    max-width: 60em;
}

.form-page .form-item .data {
    grid-template-columns: repeat(1, auto);
}
</style>
